/**
 * ScreenShotFb.java
 * 版权所有(C) 2014
 * 创建者:cuiran 2014-4-3 下午4:55:23
 */
package com.ghyf.mplay.util;


import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.ghyf.mplay.application.CookieConstants;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.bean.GlobalParamInfo;
import com.ghyf.mplay.value.ConstantValue;



import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.PixelFormat;
import android.os.Environment;
import android.view.Display;

/**
 * FrameBuffer中获取Android屏幕截图 
 * @author cuiran
 * @version 1.0.0
 */
public class ScreenShotFb {

	private static final String TAG="ScreenShotFb";
	
	final static String FB0FILE1 = "/dev/graphics/fb0";

	static File fbFile;
	 public static  Bitmap shot(){  
		 Bitmap bitmap=null;
		 try {  
    		 boolean isFlag= UserInfoSingleton.getBoolean(CookieConstants.IsPowerOff);
    		 	if(isFlag)return bitmap;
    		 /************ 创建锁对象 ************/
    	        final Object lock = new Object();
    	    	synchronized (lock) {
    	    		long start=System.currentTimeMillis();
    	    		bitmap=getScreenShotBitmap();
    	        	long end=System.currentTimeMillis();
    	        	LogUtil.i(TAG, "getScreenShotBitmap time is :"+(end-start)+" ms");
    	      
    	    	}
         }catch (Exception e) {  
         	LogUtil.e(TAG, "Exception error",e);
         }  
		 return bitmap;
	 }
	  //程序入口  
    public static  void shot1(){  
    	 try {  
    		 boolean isFlag= UserInfoSingleton.getBoolean(CookieConstants.IsPowerOff);
    		 	if(isFlag)return;
    		 /************ 创建锁对象 ************/
    	        final Object lock = new Object();
    	        
    	    	synchronized (lock) {
    	    		long start=System.currentTimeMillis();
    	    		Bitmap bitmap=getScreenShotBitmap();
    	    		
    	        	long end=System.currentTimeMillis();
    	        	LogUtil.i(TAG, "getScreenShotBitmap time is :"+(end-start)+" ms");
    	        	String filePath= ConstantValue.ROOT_SDCARD_DIR+"temp.png";
//    	        	String filePath= ConstantValue.ROOT_SDCARD_DIR+"/screens/"+System.currentTimeMillis()+".png";
    	        	ScreenShotFb.savePic(bitmap,filePath);  
    	    	}
         }catch (Exception e) {  
         	LogUtil.e(TAG, "Exception error",e);
         }  
    
    
    }  
    /**
     * Bitmap转byte[] <br>
     * 2014-10-15 上午10:54:01
     * @param bitmap
     * @return
     *
     */
    public static byte[] getBitmapByte(Bitmap bitmap){  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);  
        try {  
            out.flush();  
            out.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return out.toByteArray();  
    }  
      
     /**
      * byte[] 转 Bitmap <br>
      * 2014-10-15 上午10:54:22
      * @param temp
      * @return
      *
      */
    public static Bitmap getBitmapFromByte(byte[] temp){  
        if(temp != null){  
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);  
            return bitmap;  
        }else{  
            return null;  
        }  
    }  
    /**
     * 写文件
     * 2014-9-28 下午1:11:59
     * @param name
     * @param content
     *
     */
    public static void saveToSDCard(String name, String content) {

		 FileOutputStream fos = null;
		try{
			File file1=new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"我.txt");
			file1.createNewFile();
			
			File file = new File(ConstantValue.ROOT_DIR,name);
		    fos = new FileOutputStream(file);
		    fos.write(content.getBytes());
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	 //保存到sdcard  
	public static void savePic(Bitmap b,String strFileName){  
        FileOutputStream fos = null;  
        boolean isFlag=false;
        File fileSrc=new File(strFileName);
        try {  
        	fileSrc.createNewFile();
            fos = new FileOutputStream(strFileName);  
            if (null != fos)  
            {  
                b.compress(Bitmap.CompressFormat.PNG, 50, fos);  
                fos.flush();  
                fos.close();  
            }  
            String filePath= ConstantValue.ROOT_SDCARD_DIR+"s.png";
            File fileDst=new File(filePath);
            if(fileDst.exists()){
            	fileDst.delete();
            }
            if(fileSrc.exists()){
            	isFlag=fileSrc.renameTo(fileDst);
            }
        } catch (FileNotFoundException e) {  
        	LogUtil.e(TAG, "FileNotFoundException error",e);
        } catch (IOException e) {  
        	LogUtil.e(TAG, "IOException error",e);
        }  
        
        LogUtil.i(TAG, "savePic success isFlag="+isFlag);
    }  
	/**
	 * 获取屏幕的宽高、位深<br>
	 * 2014-12-8 下午4:04:10
	 * @param activity
	 *
	 */
	 public static void init(Activity activity){  
		
			try {
			
				Display display = activity.getWindowManager().getDefaultDisplay();
				String out=GlobalParamInfo.getInstance().getOut_resolution();
				String [] dm=out.split("x");
				if(dm==null||dm.length<=0)return;
				screenWidth = Integer.parseInt(dm[0]); // 屏幕宽（像素，如：480px）
				screenHeight = Integer.parseInt(dm[1]); // 屏幕高（像素，如：800p）
				
				int pixelformat = display.getPixelFormat();
				PixelFormat localPixelFormat1 = new PixelFormat();
				PixelFormat.getPixelFormatInfo(pixelformat, localPixelFormat1);
				 
				deepth = localPixelFormat1.bytesPerPixel;// 位深
				LogUtil.i(TAG, "deepth="+deepth+" "+screenWidth+" "+screenHeight);
				piex = new byte[screenHeight * screenWidth*deepth] ;// 像素
				colors = new int[screenHeight * screenWidth];
			}catch(Exception e){
				LogUtil.e(TAG, "Exception error",e);
			}
	 }
	
	 static byte[] piex=null;
	 static int[] colors =null;
	 static int screenWidth;
	 static int screenHeight;
	 static int deepth;
	 
	 public static synchronized Bitmap getScreenShotBitmap() {
			FileInputStream buf = null;
			try {
			
				
				fbFile = new File(FB0FILE1);

				buf = new FileInputStream(fbFile);// 读取文件内容
				DataInputStream dStream=null;
				dStream=new DataInputStream(buf);
				dStream.readFully(piex);
				dStream.close();
				
				// 将rgb转为色值
				  for(int i=0;i<(piex.length);i+=2)
		            {
					  colors[i/2]= (int)0xff000000 +
		                        (int) (((piex[i+1]) << (16))&0x00f80000)+
		                        (int) (((piex[i+1]) << 13)&0x0000e000)+
		                        (int) (((piex[i]) << 5)&0x00001A00)+
		                        (int) (((piex[i]) << 3)&0x000000f8);
		            }
				 
		       // 得到屏幕bitmap
				return Bitmap.createBitmap(colors, screenWidth, screenHeight,
	    					Bitmap.Config.RGB_565);
				
			} catch (FileNotFoundException e) {
				LogUtil.e(TAG, "FileNotFoundException error",e);
			} catch (IOException e) {
				LogUtil.e(TAG, "IOException error",e);
			}catch (Exception e) {
				LogUtil.e(TAG, "Exception error",e);
			}  
			finally {
				if(buf!=null){
					try {
						buf.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return null;
		}
	 
	public static synchronized Bitmap getScreenShotBitmap1() {
		FileInputStream buf = null;
		try {
			piex = new byte[screenHeight * screenWidth*deepth] ;// 像素
			colors = new int[screenHeight * screenWidth];
			
			fbFile = new File(FB0FILE1);
			// 初始化事件文件的权限
//						try {
//							Process sh = Runtime.getRuntime().exec("su", null, null);
//							OutputStream os = sh.getOutputStream();
//							os.write(("chmod 777 " + fbFile.getAbsolutePath()).getBytes());
//							os.flush();
//							os.close();
//							sh.waitFor();
//						} catch (Exception e) {
//							e.printStackTrace();
//						}		
			buf = new FileInputStream(fbFile);// 读取文件内容
			DataInputStream dStream=null;
			dStream=new DataInputStream(buf);
			dStream.readFully(piex);
			dStream.close();
			
			// 将rgb转为色值
			  for(int i=0;i<(piex.length);i+=2)
	            {
				  colors[i/2]= (int)0xff000000 +
	                        (int) (((piex[i+1]) << (16))&0x00f80000)+
	                        (int) (((piex[i+1]) << 13)&0x0000e000)+
	                        (int) (((piex[i]) << 5)&0x00001A00)+
	                        (int) (((piex[i]) << 3)&0x000000f8);
	            }
			 
	       // 得到屏幕bitmap
			return Bitmap.createBitmap(colors, screenWidth, screenHeight,
    					Bitmap.Config.RGB_565);
			
		} catch (FileNotFoundException e) {
			LogUtil.e(TAG, "FileNotFoundException error",e);
		} catch (IOException e) {
			LogUtil.e(TAG, "IOException error",e);
		}catch (Exception e) {
			LogUtil.e(TAG, "Exception error",e);
		}  
		finally {
			if(buf!=null){
				try {
					buf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
  
}
